package BasicClass.Three;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;

public class Test_Four {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] s = br.readLine().split(" ");
        int size = Integer.parseInt(s[0]);
        int index = Integer.parseInt(s[1]);

        Student[] students = new Student[size];
        for (int i = 0; i < size; i++) {
            String[] stu = br.readLine().split(" ");
            students[i] = new Student(Integer.parseInt(stu[0]),stu[1],Integer.parseInt(stu[2]));
        }
        int i = PayFruits(students, index);
        System.out.println(i);
    }

    private static class Student{
        int no;
        String name;
        int price;

        public Student(int no, String name, int price) {
            this.no = no;
            this.name = name;
            this.price = price;
        }
    }

    public static class MyCompStu implements Comparator<Student>{

        int o1Value = 0;
        int o2Value = 0;

        @Override
        public int compare(Student o1, Student o2) {
            if(o1.price==o2.price){
                for (char c : o1.name.toCharArray()) {
                    o1Value += c;
                }
                for (char c : o2.name.toCharArray()) {
                    o2Value += c;
                }
                return o1Value - o2Value;
            }
            return o1.price - o2.price;
        }
    }

    /**
     * 输入任意（水果ID，水果名，价格）序列，例如：1 apple 10，需要对这些序列进行排序，排序规则如下：
     * 如果水果的价格不同就按照从小到大排序，如果水果的价格相同就按照水果名的字典序从小到大排列。
     * 排序好后，购买前k种水果，并输出购买前k种水果的价格。（注意这里水果名就是任意字母组成）
     * @return
     */
    public static int PayFruits(Student[] stus,int index){
        if(stus.length==0){
            return 0;
        }
        Arrays.sort(stus,new MyCompStu());
        int count = 0;
        for (int i = 0; i < index; i++) {
            count += stus[i].price;
        }
        return count;
    }
}
